const express = require("express")
const { multer } = require("../../model/tools")
const SettingModel = require("../../model/SettingModel")
let router = express.Router()

router.get("/", async (req, res) => {
    let result = await SettingModel.find({})
    res.render("admin/setting/index.html", {
        list: result[0]
    })
})

let cpUpload = multer().fields(
    [
        { name: 'site_logo', maxCount: 1 },
        { name: 'no_picture', maxCount: 8 }
    ]
)

router.post("/doEdit", cpUpload, async (req, res) => {
    let json = {}

    // 上传多张图片的情况，需要合并json
    if (req.files.site_logo) {
        let site_logo = req.filex.site_logo[0].path.substr(7)
        json = Object.assign(json, { site_logo })
    }
    if (req.files.no_picture) {
        let no_picture = req.files.no_picture[0].path.substr(7)
        json = Object.assign(json, { no_picture })
    }

    await SettingModel.updateMany({}, Object.assign(json, req.body))

    res.redirect(`/${req.app.locals.adminPath}/setting`)

    res.send("执行增加")
})

module.exports = router